package com.lvtn.adsonandroid;

import java.util.ArrayList;


import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.lvtn.adsonandroid.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.ImageLoadingListener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class BuyActivity extends Fragment implements OnItemClickListener{
	
	private Activity activity;
	ImageLoader imageLoader;
	private static String AllBUYURL = "http://10.0.2.2/android/GetAllBuyAds.php";
	private ProgressDialog pDialog;
	JSONParser jParser = new JSONParser();
	ArrayList<Item> Data;
	JSONArray data_array = null;
	ListView list;
	ListAdapter adapter;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.activity_news, container, false);
		Data = new ArrayList<Item>();
		activity = getActivity();
		Log.d("asdasdasda","adasdada");
		list = (ListView) rootView.findViewById(R.id.listview);
		list.setOnItemClickListener(this);
		// Loading daftar rumah sakit in Background 
		//Thread
		Log.d("asdasdasda","adasdada");
		new GetAllNews().execute();
		/*
		rootView.findViewById(R.id.xemtin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity().getApplicationContext(), NewsActivity.class);
                //intent.putExtra(EXTRA_MESSAGE, data);
                startActivity(intent);
            }
        }); */
		return rootView;
	}
class GetAllNews extends AsyncTask<String, String, String> {
		
		/**
		* Before starting background thread Show Progress Dialog
		* */
			@Override
			protected void onPreExecute() {
				//Log.d("asdasdasda","adasdada");
				super.onPreExecute();
				pDialog = new ProgressDialog(activity);
				pDialog.setMessage("Loading...");
				pDialog.setIndeterminate(false);
				pDialog.setCancelable(false);
				pDialog.show();
			}
		/**
		* getting All record data from url
		* */
			protected String doInBackground(String... args) {
		// Building Parameters
			//	Log.d("asdasdasda","adasdada");
				List<NameValuePair> params = new ArrayList<NameValuePair>();
		// getting JSON string from URL
				JSONObject json = jParser.makeHttpRequest(AllBUYURL, "GET", params);
		// Check your log cat for JSON reponse
				Log.d("getAllBuyAds: ", json.toString());
				try {
		// Checking for SUCCESS TAG
					int success = json.getInt("success");
					if (success == 1) {
				// Ada record Data (SUCCESS = 1)
				// Getting Array of daftar_rs
						data_array = json.getJSONArray("news");
				// looping through All daftar_rs
						for (int i = 0; i < data_array.length(); i++) {
							JSONObject c = data_array.getJSONObject(i);
					// Storing each json item in variable
							String news_id = c.getString("id");
							String email = c.getString("user_email");
							String title = c.getString("title");
							String price = c.getString("price");
							String detail = c.getString("details");
							String link_image = c.getString("link_image");
							String status = c.getString("status");
							String date = c.getString("created_at");
							String user_name = c.getString("user_name");
							//Log.d("tenuserobj", user_name);
					// creating new HashMap
							Item objItem = new Item();
					// adding each child node to HashMap key => value
							objItem.setTitle(title);
							objItem.setPrice(price);
							objItem.setPubdate(date);
							objItem.setUser(user_name);
						//	Log.d("objsetUser",objItem.setUser(user_name));
							objItem.setLink(link_image);
							objItem.setDetail(detail);
							objItem.setId(news_id);
							objItem.setEmail(email);
							objItem.setStatus(status);
					// adding HashList to ArrayList
							Data.add(objItem);
						}
					} else {
				// Tidak Ada Record Data (SUCCESS = 0)
				// Akan menutup aplikasi
			//	Toast toast = Toast.makeText(NewsActivity.this, "Không có tin nào cả", Toast.LENGTH_SHORT);
				//toast.show();
						return null;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			return null;
			}
		/**
		* After completing background task Dismiss the progress 
		dialog
		* **/
			protected void onPostExecute(String file_url) {
		
				if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
				}
				if(null == Data || Data.size() == 0){
					Toast toast = Toast.makeText(activity.getApplicationContext(), "Không có tin nào cả", Toast.LENGTH_SHORT);
					toast.show();
				}
				else{
			// updating UI from Background Thread
					
					NewsRowAdapter objAdapter = new NewsRowAdapter(R.layout.item_list, Data);
					list.setAdapter(objAdapter);
				}
			}
		}
    // class newrowadapter
	public class NewsRowAdapter extends ArrayAdapter<Item> {
		
		
		private List<Item> items;
		private Item objBean;
		private int row;
		private DisplayImageOptions options;
		

		public NewsRowAdapter(int resource, List<Item> arrayList) {
			super( activity,resource, arrayList);
		//	this.activity = act;
			this.row = resource;
			this.items = arrayList;

			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.profile)
					.showImageForEmptyUrl(R.drawable.profile).cacheInMemory()
					.cacheOnDisc().build();
			imageLoader = ImageLoader.getInstance();

		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			View view = convertView;
			ViewHolder holder;
			if (view == null) {
				LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inflater.inflate(row, null);

				holder = new ViewHolder();
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}

			if ((items == null) || ((position + 1) > items.size()))
				return view;

			objBean = items.get(position);

			holder.tvTitle = (TextView) view.findViewById(R.id.title);
			holder.tvUser = (TextView) view.findViewById(R.id.user_name);
			holder.tvPrice = (TextView) view.findViewById(R.id.price);
			holder.tvDate = (TextView) view.findViewById(R.id.date);
			holder.imgView = (ImageView) view.findViewById(R.id.image);
			holder.pbar = (ProgressBar) view.findViewById(R.id.pbar);

			if (holder.tvTitle != null && null != objBean.getTitle()
					&& objBean.getTitle().trim().length() > 0) {
				holder.tvTitle.setText(Html.fromHtml(objBean.getTitle()));
			}
			if (holder.tvUser != null && null != objBean.getUser()
					&& objBean.getUser().trim().length() > 0) {
				Log.d("username",objBean.getUser());
				holder.tvUser.setText(Html.fromHtml(objBean.getUser()));
			}
			if (holder.tvPrice != null && null != objBean.getPrice()
					&& objBean.getPrice().trim().length() > 0) {
				holder.tvPrice.setText(Html.fromHtml(objBean.getPrice()));
			}
			if (holder.tvDate != null && null != objBean.getPubdate()
					&& objBean.getPubdate().trim().length() > 0) {
				holder.tvDate.setText(Html.fromHtml(objBean.getPubdate()));
			}
			if (holder.imgView != null) {
				if (null != objBean.getLink()
						&& objBean.getLink().trim().length() > 0) {
					final ProgressBar pbar = holder.pbar;

					imageLoader.init(ImageLoaderConfiguration
							.createDefault(activity));
					imageLoader.displayImage(objBean.getLink(), holder.imgView,
							options, new ImageLoadingListener() {
								@Override
								public void onLoadingComplete() {
									pbar.setVisibility(View.INVISIBLE);

								}

								@Override
								public void onLoadingFailed() {
									pbar.setVisibility(View.INVISIBLE);
								}

								@Override
								public void onLoadingStarted() {
									pbar.setVisibility(View.VISIBLE);

								}
							});

				} else {
					holder.imgView.setImageResource(R.drawable.ic_launcher);
				}
			}

			return view;
		}

		public class ViewHolder {

			public TextView tvTitle, tvPrice, tvDate,tvUser;
			private ImageView imgView;
			private ProgressBar pbar;

		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Item item = Data.get(position);
		Intent intent = new Intent(getActivity(), DetailSaleActivity.class);
		intent.putExtra("date", item.getPubdate());
		intent.putExtra("user_name", item.getUser());
		intent.putExtra("price", item.getPrice());
		intent.putExtra("title", item.getTitle());
		intent.putExtra("detail", item.getDetail());
		intent.putExtra("news_id", item.getId());
		intent.putExtra("user_email", item.getEmail());
		intent.putExtra("link", item.getLink());
		startActivity(intent);
	}
}